<template>
  <div class="announcement-manage-page">
    <div class="page-header">
      <h1>公告管理</h1>
      <a-button type="primary" @click="handleAdd">
        <template #icon>
          <PlusOutlined />
        </template>
        创建公告
      </a-button>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-form-item label="标题">
          <a-input 
            v-model:value="searchForm.title" 
            placeholder="请输入公告标题"
            allowClear
          />
        </a-form-item>
        
        <a-form-item label="类型">
          <a-select 
            v-model:value="searchForm.type" 
            placeholder="请选择公告类型"
            allowClear
            style="width: 120px"
          >
            <a-select-option :value="0">普通公告</a-select-option>
            <a-select-option :value="1">紧急公告</a-select-option>
            <a-select-option :value="2">维护公告</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="状态">
          <a-select 
            v-model:value="searchForm.status" 
            placeholder="请选择状态"
            allowClear
            style="width: 120px"
          >
            <a-select-option :value="0">下线</a-select-option>
            <a-select-option :value="1">正常</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button @click="handleReset" style="margin-left: 8px">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 公告表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <div class="title-cell">
              <a-tag v-if="record.isTop === 1" color="red" size="small">置顶</a-tag>
              <span>{{ record.title }}</span>
            </div>
          </template>
          
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'default'">
              {{ record.status === 1 ? '正常' : '下线' }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'publishTime'">
            {{ record.publishTime ? formatTime(record.publishTime) : '-' }}
          </template>
          
          <template v-if="column.key === 'expireTime'">
            <span :class="{ 'expired': isExpired(record.expireTime) }">
              {{ record.expireTime ? formatTime(record.expireTime) : '永久有效' }}
            </span>
          </template>
          
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button 
                v-if="record.status === 0" 
                size="small" 
                type="primary" 
                @click="handlePublish(record)"
              >
                发布
              </a-button>
              <a-button 
                v-if="record.status === 1" 
                size="small" 
                @click="handleOffline(record)"
              >
                下线
              </a-button>
              <a-popconfirm
                title="确定要删除这个公告吗？"
                @confirm="handleDelete(record)"
              >
                <a-button size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 创建/编辑公告弹窗 -->
    <AnnouncementModal
      v-model:visible="modalVisible"
      :mode="modalMode"
      :initial-data="selectedRecord"
      @success="handleModalSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { 
  listAnnouncementByPage, 
  deleteAnnouncement, 
  publishAnnouncement, 
  offlineAnnouncement 
} from '@/api/announcementController'
import AnnouncementModal from '@/components/AnnouncementModal.vue'
import dayjs from 'dayjs'

const loading = ref(false)
const dataSource = ref([])
const modalVisible = ref(false)
const modalMode = ref<'add' | 'edit'>('add')
const selectedRecord = ref(null)

const searchForm = reactive({
  title: '',
  type: undefined,
  status: undefined
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const columns = [
  {
    title: '标题',
    key: 'title',
    dataIndex: 'title',
    width: 250,
    ellipsis: true
  },
  {
    title: '类型',
    key: 'type',
    dataIndex: 'type',
    width: 100
  },
  {
    title: '状态',
    key: 'status',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '发布时间',
    key: 'publishTime',
    dataIndex: 'publishTime',
    width: 180
  },
  {
    title: '过期时间',
    key: 'expireTime',
    dataIndex: 'expireTime',
    width: 180
  },
  {
    title: '发布者',
    key: 'userName',
    dataIndex: ['user', 'userName'],
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

const loadData = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await listAnnouncementByPage(params)
    dataSource.value = response.data.data.records || []
    pagination.total = parseInt(response.data.data.total) || 0
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    type: undefined,
    status: undefined
  })
  pagination.current = 1
  loadData()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadData()
}

const handleAdd = () => {
  modalMode.value = 'add'
  selectedRecord.value = null
  modalVisible.value = true
}

const handleEdit = (record: any) => {
  modalMode.value = 'edit'
  selectedRecord.value = record
  modalVisible.value = true
}

const handlePublish = async (record: any) => {
  try {
    await publishAnnouncement(record.id)
    message.success('发布成功')
    loadData()
  } catch (error) {
    console.error('发布失败:', error)
    message.error('发布失败')
  }
}

const handleOffline = async (record: any) => {
  try {
    await offlineAnnouncement(record.id)
    message.success('下线成功')
    loadData()
  } catch (error) {
    console.error('下线失败:', error)
    message.error('下线失败')
  }
}

const handleDelete = async (record: any) => {
  try {
    await deleteAnnouncement(record.id)
    message.success('删除成功')
    loadData()
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

const handleModalSuccess = () => {
  loadData()
}

const getTypeColor = (type: number) => {
  const colors = {
    0: 'blue',    // 普通公告
    1: 'red',     // 紧急公告
    2: 'orange'   // 维护公告
  }
  return colors[type as keyof typeof colors] || 'blue'
}

const getTypeText = (type: number) => {
  const texts = {
    0: '普通',
    1: '紧急',
    2: '维护'
  }
  return texts[type as keyof typeof texts] || '普通'
}

const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const isExpired = (expireTime: string) => {
  if (!expireTime) return false
  return dayjs(expireTime).isBefore(dayjs())
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.announcement-manage-page {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.search-form {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.title-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-cell .ant-tag {
  margin: 0;
}

.expired {
  color: #ff4d4f;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

@media (max-width: 768px) {
  .announcement-manage-page {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-form :deep(.ant-form-item) {
    margin-bottom: 16px;
  }
  
  :deep(.ant-table) {
    font-size: 12px;
  }
}

/* 黑暗模式适配 */
[data-theme="dark"] .announcement-manage-page {
  background: #141414 !important;
  color: #ffffff !important;
}

[data-theme="dark"] .page-header {
  background: #1f1f1f !important;
  border-color: #404040 !important;
}

[data-theme="dark"] .page-title {
  color: #ffffff !important;
}

[data-theme="dark"] .page-description {
  color: #d1d5db !important;
}

[data-theme="dark"] .search-form {
  background: #262626 !important;
  border-color: #404040 !important;
}

[data-theme="dark"] .table-container {
  background: #1f1f1f !important;
  border-color: #404040 !important;
}

[data-theme="dark"] .title-cell {
  color: #ffffff !important;
}

[data-theme="dark"] .action-btn {
  border-color: #404040 !important;
  color: #d1d5db !important;
}

[data-theme="dark"] .action-btn:hover {
  border-color: #525252 !important;
  background: #303030 !important;
}

[data-theme="dark"] .action-btn.edit-btn:hover {
  border-color: #1890ff !important;
  color: #1890ff !important;
}

[data-theme="dark"] .action-btn.offline-btn:hover {
  border-color: #faad14 !important;
  color: #faad14 !important;
}

[data-theme="dark"] .action-btn.delete-btn:hover {
  border-color: #ff4d4f !important;
  color: #ff4d4f !important;
}

/* Ant Design 组件黑暗模式适配 */
[data-theme="dark"] :deep(.ant-table) {
  background: #1f1f1f !important;
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-table-thead > tr > th) {
  background: #262626 !important;
  color: #ffffff !important;
  border-bottom-color: #404040 !important;
}

[data-theme="dark"] :deep(.ant-table-tbody > tr > td) {
  background: #1f1f1f !important;
  color: #ffffff !important;
  border-bottom-color: #404040 !important;
}

[data-theme="dark"] :deep(.ant-table-tbody > tr:hover > td) {
  background: #262626 !important;
}

[data-theme="dark"] :deep(.ant-pagination) {
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-pagination .ant-pagination-item) {
  background: #262626 !important;
  border-color: #404040 !important;
}

[data-theme="dark"] :deep(.ant-pagination .ant-pagination-item a) {
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-pagination .ant-pagination-item-active) {
  background: #1890ff !important;
  border-color: #1890ff !important;
}

[data-theme="dark"] :deep(.ant-pagination .ant-pagination-item-active a) {
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-pagination .ant-pagination-prev),
[data-theme="dark"] :deep(.ant-pagination .ant-pagination-next) {
  background: #262626 !important;
  border-color: #404040 !important;
}

[data-theme="dark"] :deep(.ant-pagination .ant-pagination-prev a),
[data-theme="dark"] :deep(.ant-pagination .ant-pagination-next a) {
  color: #ffffff !important;
}

/* 表单组件黑暗模式适配 */
[data-theme="dark"] :deep(.ant-input) {
  background: #262626 !important;
  border-color: #404040 !important;
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-input::placeholder) {
  color: #9ca3af !important;
}

[data-theme="dark"] :deep(.ant-select-selector) {
  background: #262626 !important;
  border-color: #404040 !important;
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-select-selection-placeholder) {
  color: #9ca3af !important;
}

[data-theme="dark"] :deep(.ant-select-arrow) {
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-btn) {
  background: #262626 !important;
  border-color: #404040 !important;
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-btn:hover) {
  background: #303030 !important;
  border-color: #525252 !important;
}

[data-theme="dark"] :deep(.ant-btn-primary) {
  background: #1890ff !important;
  border-color: #1890ff !important;
}

[data-theme="dark"] :deep(.ant-btn-primary:hover) {
  background: #40a9ff !important;
  border-color: #40a9ff !important;
}

[data-theme="dark"] :deep(.ant-form-item-label > label) {
  color: #ffffff !important;
}

[data-theme="dark"] :deep(.ant-tag) {
  background: #262626 !important;
  border-color: #404040 !important;
  color: #ffffff !important;
}
</style>
